package com.jiuan.transfer.rabbitmq;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

import com.jiuan.transfer.mqtt.domain.Config;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ChannelFactory {

    private static int threadNum=3;
    private static ConnectionFactory factory;
    private static Connection connection;

    static {
        // Create a connection factory
        try {
            factory = new ConnectionFactory();
            factory.setHost(Config.getRabbit_ip());
            factory.setPort(Config.getRabbit_port());
            factory.setUsername(Config.getRabbit_username());
            factory.setPassword(Config.getRabbit_password());
            factory.setAutomaticRecoveryEnabled(true); //网络有问题时，好后可自动恢复设置。
            factory.setNetworkRecoveryInterval(10000);//10s重试一次
            //ExecutorService es = Executors.newFixedThreadPool(Config.getRabbit_connection_number());
            //connection = factory.newConnection(es);
            factory.setExceptionHandler(new MyRabbitExceptionHandler());
            connection = factory.newConnection();

        } catch (Exception e) {
            System.out.println("create connection error!");
            e.printStackTrace();

        }
    }



    public static int getThreadNum() {
        return threadNum;
    }

    public static Channel getChannel() throws IOException, TimeoutException {
        if (null == connection || !connection.isOpen()) {
            getConnection();
        }
        return connection.createChannel();
    }

    private static synchronized void getConnection() throws IOException, TimeoutException {
        connection = factory.newConnection();
    }

    /**
     * 关闭channel和connection。并非必须，因为隐含是自动调用的。
     *
     * @throws IOException
     */
    public void close() throws Exception {
        this.connection.close();
    }
}